package net.funwoo.pandago.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;

import net.funwoo.pandago.R;
import net.funwoo.pandago.util.UiUtils;

/**
 * Created by Bob Peng on 2015/5/8.
 */
public class DotView extends View {

    private Paint mPaint;
    private String mDotNumber;

    private int mDotSize = 24;

    public DotView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DotView);
        String number = a.getString(R.styleable.DotView_number);
        if (number == null) {
            number = "10";
        }
        setDotNumber(number);
        a.recycle();

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int size = UiUtils.dp2px(mDotSize);
        mPaint.setColor(getContext().getResources().getColor(R.color.red));
        canvas.drawCircle(size / 2, size / 2, mDotSize, mPaint);

        mPaint.setColor(Color.WHITE);
        mPaint.setTextSize(UiUtils.dp2px(12));
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        float textCenterX = mPaint.measureText(mDotNumber);
        float textBaselineY = getHeight() / 2 - fontMetrics.descent + (fontMetrics.descent - fontMetrics.ascent) / 2;
        canvas.drawText(mDotNumber, textCenterX, textBaselineY, mPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int size = UiUtils.dp2px(mDotSize);
        setMeasuredDimension(size, size);
    }

    public void setDotNumber(String number) {
        if (TextUtils.isEmpty(number)) {
            number = "10";
        }
        mDotNumber = number;

        invalidate();
    }
}
